package com.export;

import com.export.utils.RedisUtils;
import com.rlyy.aibase.utils.base.Box;
import com.rlyy.aibase.utils.helpers.JsonHelper;
import com.rlyy.aibase.view.key.APIKey_Enum;
import common.entity.ReflexHandler;
import common.exec.RsjIllegalArgueException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import rsj.annotation.MyScanner;

import java.util.Map;

/**
 * 启动类
 *
 * @author yuanqinglong
 * @since 2021/8/3 14:03
 */
@MyScanner(basePackages = "com.export.dao")
@ComponentScans(value = {@ComponentScan("com.export.dao")})
@SpringBootApplication
public class ExportApplication {

    public static final String TASK_LIST_KEY = "rsj|export|task";
    public static final long POP_TIMEOUT_SECOND = 3;
    protected static final Logger logger = LoggerFactory.getLogger(ExportApplication.class);
    private static Map<String, ReflexHandler> handlerMapping;

    public static void main(String[] args) {
        // SpringBoot 关闭Web功能
        ConfigurableApplicationContext applicationContext = new SpringApplicationBuilder(ExportApplication.class).web(WebApplicationType.NONE).run(args);
        handlerMapping = (Map<String, ReflexHandler>) applicationContext.getBean("handlerMapping");
        while (true) {
            handleExport(); // 导出任务
        }
    }

    public static void handleExport(){
//        long now = System.currentTimeMillis();
        Object exportRequest = RedisUtils.lLeftPop(TASK_LIST_KEY, POP_TIMEOUT_SECOND);
//        System.out.println(System.currentTimeMillis()-now);
        if(null != exportRequest){
            try {
                Box in = JsonHelper.json2Box(String.valueOf(exportRequest));
                exportTask(in);
            } catch (Exception e){
                RedisUtils.lSet(TASK_LIST_KEY, exportRequest);
                logger.error("export task has an error: ", e);
            }
        }
    }

    public static void exportTask(Box in) throws Exception{
        //Map<String, ReflexHandler> handlerMapping = (Map<String, ReflexHandler>) ApplicationContextUtil.getBean("handlerMapping");
        ReflexHandler handler = handlerMapping.get(in.getApi());
        if (handler == null) {
            throw new RsjIllegalArgueException("不存在["+in.getApi()+"]的导出方法");
        }
        Box box = (Box)handler.getMethod().invoke(handler.getBean(),in);
        logger.info("导出完成。tid:[{}],api:[{}]", in.getValue(APIKey_Enum.TID.getKey()), in.getApi());
    }
}
